<?php
namespace Admin\Controller;
use Think\Controller;
class PublicController extends Controller {
	function _initialize() {
		//查list;
		import('ORG.Util.Operation');
		$operation_obj = new \Org\Util\Operation();
		//$log_list = $operation_obj -> logList(array('member_id' => 2086));
		//记录日志
		//$operation_obj -> checkTableIsExist();//创建日志记录表，如果不存在则新建
		$operation_obj -> writeLog(APP_NAME.'_'.MODULE_NAME .'_'.ACTION_NAME,'系统后台用户登录操作');
	}
	public function index() {
		$sessionid=session('user');
		if (isset ($sessionid)) {
			$this->redirect('Index/index');
		} else {
			$this->display();
		}
	}
	// 用户登出
	public function logout() {
		$sessionid=session('user');
		if (isset ($sessionid)) {
			session('user',null);
			//session_destroy();
			$this->assign("jumpUrl", __URL__ . '/index/');
			$this->success('登出成功！', 1);
		} else {
			$this->success('已经登出！', 1);
		}
	}
	// 登录检测
	public function checkLogin() {
		$account=I('account');
		$password=md5(I('password'));
		$verify=md5(I('verify'));
		if (empty ($account)) {
			$this->error('帐号必须！');
		}
		if (empty ($password)) {
			$this->error('密码必须！');
		}
		$login=array();
		//使用用户名、密码和状态的方式进行认证
		//dump($map);
		//dump($authInfo);
		$con['account']=$account;
		$con['password']=$password;
		$user = M('User');
		$userlist=$user->where($con)->select();
		// dump($userlist);
		if (!$userlist) {
			$this->error('用户名或密码错误', 0);
		} 
		else 
		{
			$User = M('User');
			$ip = get_client_ip();
			$time = time();
			$data = array ();
			$data=$userlist[0];
			$data['id'] = $userlist[0]['id'];
			$data['last_login_time'] = $time;
			$data['login_count'] = array (
				'exp',
				'login_count+1'
			);
			$data['last_login_ip'] = $ip;
			$userlist=$User->create($data);
			
			if($User->save($userlist)){
				$user = D('User');
				$usersessionlist=$user->relation(true)->find($userlist['id']);
				session('user',$usersessionlist);
				//取出相关角色信息
				$ru = M('role_user');
				$con['uid'] = $userlist['id'];
				$rul = $ru->where($con)->select();
				$role = M('role');
				$con1['id'] = $rul[0]['group_id'];
				$rl = $role->where($con1)->select();
				//dump($role->getLastSql());
				session('user.role',$rl[0]);
				//取出相关可访问资源信息
				$node = M('node');
				$con2['id'] = array('in',$rl[0]['rules']);
				$node = $node->where($con2)->select();
				session('user.nodes',$node);
				//重组权限节点为数组
				if(session('user.account')=='admin'){
					$node = M('node');
					$node = $node->select();
					session('user.nodes',$node);
					foreach (session('user.nodes') as $key => $value) {
						$nodesname[$key]=$value['name'];
						session('user.nodesname',$nodesname); 
					}
				}else{
					foreach (session('user.nodes') as $key => $value) {
						$nodesname[$key]=$value['name'];
						session('user.nodesname',$nodesname); 
					}
				}
				//取出所在项目组的信息
				// $groups = M('groups');
				// $con2['id'] = array('in',$userlist['groupsid']);
				// $groups = $groups->where($con2)->select();
				
				$auth = new \Think\Auth();
				$groups=$auth->getGroups(session('user.id'));
				session('user.groups',$groups[0]);
				$this->success('登录成功！', 1);
			}else{
				$this->error('登录失败！请检查存入session错误！', 1);
			}
			
			
		}
	}
	public function verify() {
		$type = isset ($_GET['type']) ? $_GET['type'] : 'gif';
		import("@.ORG.Util.Image");
		Image :: buildImageVerify(4, 1, $type);
	}
	//添加用户提交处理  
	public function reg() {
		$m = D("User");
		$_POST['password'] = md5(123456);
		$groupsIds = $_POST['groupsIds'];
		$groupsIdsstr = implode(",", $groupsIds);
		$_POST['groupsid'] = $groupsIdsstr;
		//dump($_POST);
		if (!$m->create($_POST)) {
			$this->error($m->getError(), 3);
		} else {
			if ($result = $m->add()) {
				$this->addRole($result, 2);
				$this->addGroup($result, $groupsIds);
				$this->success('添加用户成功！', 1);
			} else {
				$this->error('添加用户失败！'.$m->getError(), 0);
			}
		}
	}
	protected function addRole($userId, $roleId) {
		//注册用户自动加入相应权限组
		$RoleUser = M("role_user");
		$data['user_id'] = $userId;
		$data['role_id'] = $roleId;
		$RoleUser->create($data);
		$RoleUser->add($data);
	}
	protected function addGroup($userId, $groupsIds) {
		//用户加入相应项目组
		$RoleUser = M("groups_user");
		foreach ($groupsIds as $key => $v) {
			//$userlist[$key]=$v[id];
			$data['user_id'] = $userId;
			$data['groups_id'] = $v;
			$RoleUser->create($data);
			$RoleUser->add($data);
		}

	}
	public function publicprojectview() {
		$n = M("Groups");
		import("ORG.Util.Page"); //导入分页类
		$count = $n->count(); //计算总数
		//$p = new Page($count,$rows);order($sort+','+$order)->
		$list = $n->order('gname desc')->select();
		//$list = $n->select();
		$list = json_encode($list);
		$result = '{"total":' . $count . ',"rows":' . $list . '}';
		echo ($list); //输出json数据 
	}
	public function uploadfile(){
		$type = $_REQUEST['type'];
		$imgurl = $_REQUEST['imgurl'];
		$res = array();
		if (!empty($_FILES)) {
			import("ORG.Net.UploadFile");
			$upload = new UploadFile();
			$upload -> maxSize = 2048000;
			$upload -> allowExts = array('jpg', 'jpeg', 'gif', 'png');
			$upload -> savePath = "./Weixin/Tpl/Res/upload/";
			$upload -> saveRule= 'my_filename';
			//$upload -> saveRule = uniqid;
			 $upload->thumb = true; //设置缩略图
			 $upload->thumbType=0;//0按照等比例进行缩放
			// $upload->imageClassPath = "ORG.Util.Image";
			// $upload->thumbPrefix = "130_,75_,24_"; //生成多张缩略图
			// $upload->thumbMaxWidth = "130,75,24";
			// $upload->thumbMaxHeight = "130,75,24";
			 $upload->thumbMaxWidth = "500";
			 $upload->thumbMaxHeight = "500";//上传规则
			$upload -> thumbRemoveOrigin = true;//删除原图

			if (!$upload -> upload()) {
				//$this->error($upload->getErrorMsg());//获取失败信息
				$this -> error('失败！'.$upload -> getErrorMsg(), 0);
				$res['error'] = 0;
				$res['msg'] = $upload -> getErrorMsg();
				$res['imgurl'] = '失败！';
			} else {
				if (!empty($imgurl)) {
					$flag = unlink("./Weixin/Tpl/Res/upload/" . $imgurl);
				}
				$info = $upload -> getUploadFileInfo();
				//获取成功信息
				$res['error'] = 1;
				$res['msg'] = "成功！---" . $flag;
				$res['imgurl'] = "thumb_".$info[0]['savename'];
			}
		} else {
			$res['error'] = 0;
			$res['msg'] = "请选择上传文件！";
			$res['imgurl'] = null;
		}
		echo json_encode($res);
	}
}
?>